//
// Thread.cpp
//
// $Id: //poco/1.4/Foundation/src/Thread.cpp#2 $
//
// Library: Foundation
// Package: Threading
// Module:  Thread
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier:	BSL-1.0
//


#include "Poco/Thread.h"
#include "Poco/Mutex.h"
#include "Poco/Exception.h"
#include "Poco/AtomicCounter.h"
#include <sstream>


#if defined(POCO_OS_FAMILY_UNIX)
#include "Thread_POSIX.cpp"
#endif


namespace Poco {

Thread::Thread(): 
	m_id(uniqueId()), 
	m_name(makeName())
	//m_pTLS(0),
	//m_event(true)
{
}


Thread::Thread(const std::string& name): 
	m_id(uniqueId()), 
	m_name(name)
	//m_pTLS(0),
	//m_event(true)
{
}


Thread::~Thread()
{
	//delete m_pTLS;
}


void Thread::setPriority(ThreadPriority prio)
{
	setPriorityImpl(prio);
}


ThreadPriority Thread::getPriority() const
{
	return ThreadPriority(getPriorityImpl());
}


void Thread::start(Runnable& target)
{
	startImpl(target);
}


// void Thread::start(Callable target, void* pData)
// {
// 	startImpl((std::shared_ptr<Runnable>)new CallableHolder(target, pData));
// }


void Thread::join()
{
	joinImpl();
}


void Thread::join(long milliseconds)
{
	if (!joinImpl(milliseconds))
		throw TimeoutException();
}


bool Thread::tryJoin(long milliseconds)
{
	return joinImpl(milliseconds);
}

/*
bool Thread::trySleep(long milliseconds)
{
// 	Thread* pT = Thread::current();
// 	poco_check_ptr(pT);
// 	return !(pT->m_event.tryWait(milliseconds));
	return !(m_event.tryWait(milliseconds));
}


void Thread::wakeUp()
{
	m_event.set();
}*/


// ThreadLocalStorage& Thread::tls()
// {
// 	if (!m_pTLS)
// 		m_pTLS = new ThreadLocalStorage;
// 	return *m_pTLS;
// }
// 
// 
// void Thread::clearTLS()
// {
// 	if (m_pTLS)
// 	{
// 		delete m_pTLS;
// 		m_pTLS = 0;
// 	}
// }


std::string Thread::makeName()
{
	std::ostringstream name;
	name << '#' << m_id;
	return name.str();
}


int Thread::uniqueId()
{
	static Poco::AtomicCounter counter;
	return ++counter;
}


void Thread::setName(const std::string& name)
{
	FastMutex::ScopedLock lock(m_mutex);

	m_name = name;
}


} // namespace Poco
